import React ,{useState} from 'react'
import { Input } from 'antd';
import {useDispatch,useSelector} from "react-redux"
import * as api from "./api/index"
import My_model from './components/My_model';

function ToduList() {
    const dispatch = useDispatch()
    const [value,setValue] = useState("")
    const [edit_value,setEdit_value] = useState("")
    const [count,setCount] = useState(0)
    const [isModalVisible, setIsModalVisible] = useState(false);

    // 从仓库里取数据
    const data = useSelector((state)=>{
        return state.todu_reduce.data
    })
    //回车事件函数
    const add_data = () => { 
        dispatch(api.add_data(value))
        setValue("")
    }

    // 删除函数
    const del_data = (index) => { 
        console.log(index);
        dispatch(api.del_data(index))
    }
  
    // 编辑函数
    const edit_data = (item,index) => {
        setEdit_value(item)
        setCount(index)
        setIsModalVisible(true);
    };
    
    const handleOk = (value) => {
        console.log(value);
        let obj = {
            value,
            count
        }
        dispatch(api.edit_data(obj))
        setIsModalVisible(false);
    };
    
    const handleCancel = () => {
        setIsModalVisible(false);
    };

    let my_model = {
        isModalVisible,
        handleCancel,
        handleOk,
        edit_value
    }
    return (
        <div>ToduList
            <Input 
                style={{width:"200px"}}
                value={value}
                placeholder="Basic usage" 
                onChange={(e)=>setValue(e.target.value)} 
                // 回车事件
                onPressEnter={add_data}
                />
            {
                data&&data.length>0?data.map((item,index)=>{
                    return <div key={index}>
                        <div> {item} 
                            <button onClick={()=>edit_data(item,index)}>编辑</button>
                            <button onClick={()=>del_data(index)}>删除</button>
                        </div>
                        </div>
                }):"没有数据"
            }
            <My_model {...my_model}></My_model>
        </div>
    )
}

export default ToduList